var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var webim = global.webim;
var webimhandler = global.webimhandler;
import Serv from './meServ';
var regeneratorRuntime = require("../../../lib/js/runtime-module.js")
var posterHandle = require("../../template/poster_handle.js");
//获取应用实例
var app = getApp();
Page(Object.assign({}, posterHandle,baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    employeeMsg:"",
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    openBoss:false,
    employeeData:'',
    employee:{},
    uploadParams:{},
    userInfo:{},
    defBgImg: [
      cf.config.posterOssHost + "poster/share1.png",
      cf.config.posterOssHost + "poster/share2.png",
      cf.config.posterOssHost + "poster/share3.png",
      cf.config.posterOssHost + "poster/share4.png"
    ],
    posterUrl: "",
    commonStylePosterUrl: ""
  },
  getEmployeeInfo(){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/employee/getEmployeeInfo",
      data: {
        cusmallToken: cusmallToken,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        var employee = data.model && data.model.employee
        if (data && 0 === data.ret && employee && employee.wxBind && (employee.powerSwitch & (Math.pow(2, 0))) != 0) {
          ctx.setData({
            isSales:true,
            employee:data.model.employee
          })
          wx.removeStorageSync("employee");
          wx.setStorageSync("employee",data.model.employee);
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  linkDetail:function (){
    wx.navigateTo({
      url: '/subPackages2/pages/customer/customer',
    });
  },
  toDetail:function (e){
    let {type} = e.currentTarget.dataset
    console.log(type)
    wx.navigateTo({
      url: '/subPackages2/pages/ReceptionSubscribe/ReceptionSubscribe?type='+type,
    });
  },
  linkposter:function (){
    var ctx = this;
    wx.navigateTo({
      url: '/pages/canvas/index?eId=' + ctx.data.employeeMsg.id,
    });
  },
  linkCusPoster(){

    var ctx = this;
    wx.navigateTo({
      url: '/pages/canvas/cus_poster?eId=' + ctx.data.employeeMsg.id,
    });
  },
  //跳转到首页
  toIndex(){
    wx.switchTab({
      url:'/pages/index/index'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData)
    wx.hideShareMenu()
    var ctx = this;
    let phoneNo =  wx.getStorageSync('phoneNo');
    this.getQueryEmployeeDataByPhone(phoneNo)
    this.aliyunUploadToken();//获取阿里云签名
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      let companyMsg = wx.getStorageSync('companyInfo');
      ctx.getEmployeeInfo();
      ctx.setData({
        companyMsg: companyMsg,
        mallEnable:wx.getStorageSync("visitCardConfig").mallEnable
      })
    });
  },

  async getQueryEmployeeDataByPhone(phoneNo){
    var ctx = this;
    let { data, msg,code }= await Serv.getQueryEmployeeDataByPhone(phoneNo)
    if (msg=='success' && code =='200') {
      // wx.hideLoading();
      console.log(data)
      ctx.setData({
        employeeData:data
      })
    }
    // console.log(data)
  },

  getEmployeeInfo() {
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/employee/getEmployeeInfo",
      data: {
        cusmallToken: cusmallToken,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        var employee = data.model.employee
        if (data && 0 === data.ret && employee) {
          let openBoss = employee.powerSwitch;
          ctx.setData({
            employeeMsg:employee,
            employee:data.model.employee
          })
          if ((openBoss & (Math.pow(2, 1))) != 0) {
            ctx.setData({
              openBoss: true
            })
          }
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  //获取海报二维码
  getUserInfo: function () {
    let eid = wx.getStorageSync('employee').id
    let _this = this;
    // wx.showLoading({ title: '生成海报中' });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/employee/generateShareQrCode',
      data: {
        cusmallToken: cusmallToken,
        eid,
        page: "pages/mycard/card"
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        let data = res.data;
        if (data && data.ret == 0) {
          let employee = data.model.employee;
          let model = data.model;
          let userInfo = {};
          //这个是为了兼容以前 旧头像的问题 ，因为以前旧头像存的是全路径，
          //但是之后改成https 之前http方式的头像就不能用了，
          //想去下面的代码 可以叫后台把数据库 http的头像替换成https
          if (employee.headPic && employee.headPic.indexOf("https://") < 0) {//微信头像 把http换成https
            employee.headPic = employee.headPic.replace(cf.config.userImagePath, cf.config.downLoadUploadPath);
          }

          userInfo.headPic = employee.headPic;//头像是全路径
          userInfo.logo = cf.config.downLoadUploadPath + model.headImg;
          userInfo.cardStyleId = employee.cardStyleId || 1;
          userInfo.salesProductName = employee.salesProductName || '' //主推项目
          // userInfo.email = employee.email;
          userInfo.customStyle = employee.customStyle;
          userInfo.sharePic = employee.sharePic || _this.data.defBgImg[0];
          userInfo.name = employee.name || employee.nickName || "-";//姓名
          if (userInfo.name.length > 4) {
            userInfo.name = userInfo.name.substring(0, 4) + "...";
          }
          userInfo.postLen = 0;
          var nameArr = userInfo.name.split("");
          for (let ch of nameArr) {
            if (/[a-z]|[\s]/.test(ch)) {
              userInfo.postLen += 0.5;
            } else if (/[A-Z]/.test(ch)) {
              userInfo.postLen += 0.7;
            } else if (/[\.]/.test(ch)) {
              userInfo.postLen += 0.2;
            } else {
              userInfo.postLen += 1;
            }
          }
          userInfo.post = employee.post;//职位

          userInfo.phone = employee.telephone||employee.phone||'-';//登录手机
          // userInfo.telephone = employee.telephone || "";//工作手机
          // userInfo.wxAccount = employee.wxAccount;//微信号
          userInfo.location = model.location||'-';//地址

          // userInfo.company = employee.company || model.company || "-";

          if (model.appletScene && model.appletScene.qrcodeUrl) {
            // userInfo.qrcode = cf.config.downLoadUploadPath+model.appletScene.qrcodeUrl;//二维码
            userInfo.qrcode = model.appletScene.qrcodeUrl;//二维码

          }

          _this.setData({ userInfo });

          let updataCard1 = wx.getStorageSync('updataCard1')
          let updataCard2 = wx.getStorageSync('updataCard2')
          if(updataCard1){
          _this.drawNewCardStyle();

          }
          if(updataCard2){
          _this.drawPosterCus();
          }


        //   if (0 == userInfo.cardStyleId) {
        //     _this.drawPoster();
        //   } else {
        //     if (10 < userInfo.company.length) {
        //       userInfo.company = userInfo.company.substring(0, 9) + "...";
        //     }
        //     if (10 < userInfo.post.length) {
        //       userInfo.post = userInfo.post.substring(0, 9) + "...";
        //     }
        //     // if (10 < userInfo.location.length) {
        //     //   userInfo.location = userInfo.location.substring(0, 10) + "...";
        //     // }
        //     _this.drawNewCardStyle();
        //     // _this.drawPosterCus();
        //   }
        } else {
        }
      },
      complete: function () {
      }
    })
  },
  drawPosterCus: function (cb) {
    // debugger
    // wx.showLoading({ title: '生成海报中' });
    let _this = this;
    let userInfo = _this.data.userInfo;
    let ctx = wx.createCanvasContext('myCanvas2');
    let pxRatio = wx.getSystemInfoSync().screenWidth / 750;
    pxRatio *= 2;
    let imgUrl = _this.data.downLoadResPath + "/huiketui/mobile/image/poster/";
    let imgUrl2 = _this.data.downLoadResPath + "/huiketui/mobile/image/";
    let phoneIcon = 'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/poster/icon_01_shouji.png'
    let canvasWidth = 640 * pxRatio, canvasHeight = 946 * pxRatio;
    let drawEle = [
      //背景
      { type: "rect", x: 0 * pxRatio, y: 0 * pxRatio, width: canvasWidth, height: canvasHeight, url: "", fontSize: 0, color: "#FFFFFF", text: "" },
      //用户自定义图片
      { type: "img", x: 0 * pxRatio, y: 0 * pxRatio, width: 568 * pxRatio, height: 648 * pxRatio, url: userInfo.sharePic },
      //用户头像
      { type: "img", x: 25 * pxRatio, y: 672 * pxRatio, width: 99 * pxRatio, height: 99 * pxRatio, url: userInfo.headPic },
      //姓名
      { type: "txt", x: 143 * pxRatio, y: 710 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 30 * pxRatio, color: "#333", text: userInfo.name },
      //职位
      { type: "txt", x: (153 * pxRatio + 32 * pxRatio * userInfo.postLen), y: 710 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 24 * pxRatio, color: "#999", text: '' },
      //描述 项目名称
      { type: "txt", x: 143 * pxRatio, y: 750 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 24 * pxRatio, color: "#999", text: userInfo.salesProductName||'美的置业' },
      //电话图标
      { type: "img", x: 25 * pxRatio, y: 790 * pxRatio, width: 24 * pxRatio, height: 29 * pxRatio, fontSize: 24 * pxRatio, url: phoneIcon },
      //联系电话

      { type: "txt", x: 60 * pxRatio, y: 815 * pxRatio, width: 350 * pxRatio, height: 30 * pxRatio, fontSize: 24 * pxRatio, color: "#333", text: userInfo.telephone||userInfo.phone },
      { type: "txt", x: 385 * pxRatio, y: 820 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 24 * pxRatio, color: "#888", text: "长按识别二维码" },
      //二维码图

    ];
    if (_this.data.textList && _this.data.textList.length > 0 && cb) {
      // debugger
      for (let i = 0; i < _this.data.textList.length; i++) {
        let textItem = _this.data.textList[i];
        drawEle.push({
          type: "txt", x: textItem.x * pxRatio * 2, y: (textItem.y * pxRatio * 2) + (38 * textItem.scale), fontSize: 32 * textItem.scale * pxRatio, color: "#fff", text: textItem.text
        });
      }
    }
    if (userInfo.qrcode) {
      // debugger
      drawEle.push({ type: "img", x: 410 * pxRatio, y: 665 * pxRatio, width: 120 * pxRatio, height: 120 * pxRatio, url: userInfo.qrcode })
    } else {
      //drawEle.push({ type: "img", x: 465 * pxRatio, y: 754 * pxRatio, width: 120 * pxRatio, height: 120 * pxRatio, url: imgUrl + "qr_img.jpg" })
    }
    _this.drawPostDetailCommon(ctx, drawEle, 0, 700, 1000, function () {
      wx.hideLoading();
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas2',
        success: function (res) {
          _this.aliUpload(res.tempFilePath, 'special', false);
          // _this.setData({ posterUrl: res.tempFilePath,svaeBtn2:true});
          wx.removeStorageSync('updataCard2')
          wx.hideLoading();
          _this.setData({svaeBtn2:true,updataCard2:false});
          cb && cb();
        }
      });
    });
  },
  drawNewCardStyle() {
    console.log('生成名片海报中...')
    // debugger
    // https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/card/card-02.png
    let _this = this;
    let userInfo = _this.data.userInfo;
    let ctx = wx.createCanvasContext('commonStyleCard');
    let pxRatio = wx.getSystemInfoSync().screenWidth / 750;
    pxRatio *= 2;
    // let imgUrl = _this.data.downLoadResPath + "/huiketui/mobile/image/cardstyle/";
    let imgUrl = `https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/poster/`
    let canvasWidth = 640 * pxRatio, canvasHeight = 850 * pxRatio;
    userInfo.cardStyleImg = imgUrl + "card-0" + userInfo.cardStyleId + ".png";
    let translateX = 0;
    let infoCount = 0;
    let qrCodeText = `长按识别二维码 收下${app.globalData.cardTitle}`

    if (userInfo.phone) {
      userInfo.phoneCount = infoCount;
      infoCount++;
    }
    console.log(infoCount)
    // console.log(userInfo)
    let drawEle = [
      //背景 index 0
      { type: "rect", x: 0 * pxRatio, y: 0 * pxRatio, width: canvasWidth, height: canvasHeight, url: "", fontSize: 0, color: "#fff", text: "" },
      //用户头像 index 1
      { type: "img", x: 320 * pxRatio, y: 25 * pxRatio, width: 340 * pxRatio, height: 340 * pxRatio, url: userInfo.headPic },
      //卡片样式 图片 index 2
      { type: "img", x: 15 * pxRatio, y: 10 * pxRatio, width: 610 * pxRatio, height: 370 * pxRatio, url: userInfo.cardStyleImg },
      //姓名 index 3
      { type: "txt4", x: 52 * pxRatio, y: 100 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 32 * pxRatio, color: "#333", text: userInfo.name },
      //职位 index 4
      { type: "txt", x: (52+userInfo.name.length*35) * pxRatio, y: 100 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#333", text: '' },
      //电话图标 5
      { type: "img", x: 52 * pxRatio, y: (210 + userInfo.phoneCount * 45) * pxRatio, width: 23 * pxRatio, height: 23 * pxRatio, url: imgUrl + "icon_0" + userInfo.cardStyleId + "_tel.png" },
      //联系电话 6
      { type: "txt", x: 85 * pxRatio, y: (227 + userInfo.phoneCount * 45) * pxRatio, width: 350 * pxRatio, height: 30 * pxRatio, fontSize: 22 * pxRatio, color: "#888", text:userInfo.phone },
      //地址图标 7
      { type: "img", x: 52 * pxRatio, y: 257 * pxRatio, width: 21 * pxRatio, height: 24 * pxRatio, url: imgUrl + "icon_0" + userInfo.cardStyleId + "_addr.png" },
      //联系地址 8
      { type: "txt2", x: 85 * pxRatio, y: 277* pxRatio, width: 250 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#666", text: userInfo.location||'暂无信息' },
      // { type: "txt", x: 85 * pxRatio, y: 307* pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#666", text: addr2||'' },
      // { type: "txt", x: 85 * pxRatio, y: 337 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#666", text: addr3||''},
      { type: "img", x: (640 - 200) / 2 * pxRatio, y: 470 * pxRatio, width: 200 * pxRatio, height: 200 * pxRatio, url: userInfo.qrcode },
      { type: "txt3", x: 320 * pxRatio, y: 740 * pxRatio, width: 640 * pxRatio, height: 40 * pxRatio, fontSize: 26 * pxRatio, color: "#333", text: qrCodeText },
      {type:'rect',x:(640-15)*pxRatio,y:0*pxRatio,width:15*pxRatio,height:400*pxRatio,url:'',fontSize:0,color:'#fff',text:''}
      //二维码提示 9
      //二维码图 10
      // { type: "circle", x: (640 - 110 + 110) / 2 * pxRatio, y: 570 * pxRatio, width: 240 * pxRatio, height: 240 * pxRatio, r: 120 * pxRatio,color:"red" }
    ];
    // debugger
    var len;
    if (2 == userInfo.cardStyleId) {
      //重写用户头像位置
      drawEle[1] = { type: "img", x: 25 * pxRatio, y: 25 * pxRatio, width: 340 * pxRatio, height: 340 * pxRatio, url: userInfo.headPic };
      // drawEle[3] = { type: "img", x: 345 * pxRatio, y: 270 * pxRatio, width: 30 * pxRatio, height: 30 * pxRatio };
      //公司名
      // drawEle[4] = { type: "txt2", x: 380 * pxRatio, y: 290 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, lineH: 30 * pxRatio, fontSize: 22 * pxRatio, color: "#212121", text: '' };
      //名字
      drawEle[3] = { type: "txt4", x: 344 * pxRatio, y: 120 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 30 * pxRatio, color: "#333333", text: userInfo.name };
      //职位
      // len = _this.strTolen(userInfo.name);
      drawEle[4] = { type: "txt", x: 350 * pxRatio, y: 155 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#666666", text: '' };
      //电话图标 5
      drawEle[5] = { type: "img", x: canvasWidth - 70 * pxRatio, y: 210 * pxRatio, width: 23 * pxRatio, height: 23 * pxRatio, url: imgUrl + "icon_0" + userInfo.cardStyleId + "_tel.png" };
      //联系电话
      drawEle[6] = { type: "txt1", x: canvasWidth - 80 * pxRatio, y: 230 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 24 * pxRatio, color: "#333333", text:userInfo.phone };
      //联系地址 图标3
      drawEle[7] = { type: "img", x: canvasWidth - 70 * pxRatio, y: 250 * pxRatio, width: 21 * pxRatio, height: 24 * pxRatio, url: imgUrl + "icon_0" + userInfo.cardStyleId + "_addr.png" };
      //联系地址
      // let addr = userInfo.location
      // let addrLen = addr.length
      // let addr1 = addr.substring(0, 12)
      // let addr2 = addr.substring(12, 24)
      // let addr3 = addr.substring(24, 34)+'...'
      // debugger
      drawEle[8] = { type: "txt1", x: canvasWidth - 80 * pxRatio, y: 270 * pxRatio, width: 270 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#333333", textAlign: 'right', text: userInfo.location||'暂无信息' };
      // drawEle[9] = { type: "txt1", x: canvasWidth - 80 * pxRatio, y: 300 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#333333", textAlign: 'right', text: addr2||'' };
      // drawEle[10] = { type: "txt1", x: canvasWidth - 80 * pxRatio, y: 330 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#333333", textAlign: 'right', text: addr3||'' };

    } else if (3 == userInfo.cardStyleId) {
      //重写用户头像位置
      drawEle[1] = { type: "img", x: 36 * pxRatio, y: 33 * pxRatio, width: 145 * pxRatio, height: 145 * pxRatio, url: userInfo.headPic };
      //名字
      drawEle[3] = { type: "txt4", x: 200 * pxRatio, y: 123 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 44 * pxRatio, color: "#fff", text: userInfo.name };
      //职位
      drawEle[4] = { type: "txt", x: (200+userInfo.name.length*50) * pxRatio, y: 120 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 30 * pxRatio, color: "#fff", text: '' };
      //电话图标1
      drawEle[5] = { type: "img", x: 85 * pxRatio, y: (242 + userInfo.phoneCount * 40) * pxRatio, width: 20 * pxRatio, height: 20 * pxRatio, url: imgUrl + "icon_0" + userInfo.cardStyleId + "_tel.png" };
      //联系电话
      drawEle[6] = { type: "txt", x: 120 * pxRatio, y: (260 + userInfo.phoneCount * 40) * pxRatio, width: 350 * pxRatio, height: 30 * pxRatio, fontSize: 22 * pxRatio, color: "#333", text:userInfo.phone };
      drawEle[7] = { type: "img", x: 85 * pxRatio, y: 282  * pxRatio, width: 20 * pxRatio, height: 20 * pxRatio, url: imgUrl + "icon_0" + userInfo.cardStyleId + "_addr.png" };
      //联系地址
      // let addr = userInfo.location
      // let addrLen = addr.length
      // let addr1 = addr.substring(0, 20)
      // let addr2 = addr.substring(20, 40)
      // let addr3 = addr.substring(40, addr.length)
      drawEle[8] = { type: "txt2", x: 120 * pxRatio, y: 300 * pxRatio, width: 400 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#333333",text: userInfo.location||'暂无信息' };
      // drawEle[9] = { type: "txt", x: 120 * pxRatio, y: 335 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#333333",text: addr2||'' };
      // drawEle[10] = { type: "txt", x: 120 * pxRatio, y: 370 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#333333",text: addr3||'' };
    } else if (4 == userInfo.cardStyleId) {
      drawEle[1] = { type: "img", x: 85 * pxRatio, y: 33 * pxRatio, width: 145 * pxRatio, height: 145 * pxRatio, url: userInfo.headPic };
      //名字
      drawEle[3] = { type: "txt4", x: 100 * pxRatio, y: 270 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 40 * pxRatio, color: "#333", text: userInfo.name };
      //职位
      drawEle[4] = { type: "txt", x: 100 * pxRatio, y: 320 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 28 * pxRatio, color: "#666", text: '' };

      //电话图标1
      drawEle[5] = { type: "img", x: 290* pxRatio, y: (225 + userInfo.phoneCount * 40) * pxRatio, width: 23 * pxRatio, height: 23 * pxRatio, url: imgUrl + "icon_0" + userInfo.cardStyleId + "_tel.png" };
      //联系电话
      drawEle[6] = { type: "txt", x: 315 * pxRatio, y: (245 + userInfo.phoneCount * 40) * pxRatio, width: 350 * pxRatio, height: 30 * pxRatio, fontSize: 22 * pxRatio, color: "#666", text:userInfo.phone };
      //图标3
      drawEle[7] = { type: "img", x: 290 * pxRatio, y: 265 * pxRatio, width: 21 * pxRatio, height: 24 * pxRatio, url: imgUrl + "icon_0" + userInfo.cardStyleId + "_addr.png" };
      //联系地址
      // let addr = userInfo.location
      // let addrLen = addr.length
      // let addr1 = addr.substring(0, 12)
      // let addr2 = addr.substring(12, 24)
      // let addr3 = addr.substring(24, 34)+'...'
      drawEle[8] = { type: "txt2", x: 315 * pxRatio, y: 285* pxRatio, width: 260 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#666", text: userInfo.location||'暂无信息' };
      // drawEle[9] = { type: "txt", x: 315 * pxRatio, y: 320 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#666",text: addr2||'' };
      // drawEle[10] = { type: "txt", x: 315 * pxRatio, y: 350 * pxRatio, width: 350 * pxRatio, height: 40 * pxRatio, fontSize: 22 * pxRatio, color: "#666",text: addr3||'' };
    }
    _this.drawPostDetail(ctx, drawEle, 0, canvasWidth, canvasHeight, function () {
      wx.hideLoading();
      wx.canvasToTempFilePath({
        canvasId: 'commonStyleCard',
        success: function (res) {
          _this.aliUpload(res.tempFilePath, 'card', false);
          wx.removeStorageSync('updataCard1')
          _this.setData({updataCard1:false});
        }
      });
    });

  },

  //绘制名片海报
  drawPostDetail: function (cxt, drawEle, idx, drawWidth, drawHeight, callback) {
    let _this = this;
    if (idx == drawEle.length) {
      cxt.draw();
      setTimeout(function () {
        callback();
      }, 400)
      return;
    }
    let ele = drawEle[idx++]
    if(ele.type&&ele.type=='txt2'){
      console.log(ele.x, ele.y)
    }
    switch (ele.type) {
      case "img":
        wx.downloadFile({
          url: ele.url,
          success: function (res) {
            console.log(ele.x, ele.y)

            cxt.drawImage(res.tempFilePath, ele.x, ele.y, ele.width, ele.height);
          },
          fail: function (e) {
            console.log(e)
          },
          complete: function () {
            _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
          }
        });
        break;
      case "txt":
        cxt.setFillStyle(ele.color);
        cxt.setFontSize(ele.fontSize);
        cxt.fillText(ele.text, ele.x, ele.y);
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        // debugger
        break;
      case "txt1":
        cxt.setFillStyle(ele.color);
        cxt.setFontSize(ele.fontSize);
        cxt.setTextAlign('right')
        // debugger
        let chr1 = ele.text.split("");
        let row1 = [];
        let temp1 = "";
        for (let i = 0; i < chr1.length; i++) {
          if (cxt.measureText(temp1).width < ele.width) {
            temp1 += chr1[i];
          } else {
            i--;
            row1.push(temp1);
            temp1 = "";
          }
        }
        row1.push(temp1);
        if (row1.length > 3) {//最多换行2行
          let rowCut1 = row1.slice(0, 3);
          let rowPart1 = rowCut1[1];
          let test1 = "";
          let empty1 = [];
          for (let i = 0; i < rowPart1.length; i++) {
            if (cxt.measureText(test1).width < ele.width - 20) {
              test1 += rowPart1[i];
            } else {
              break;
            }
          }
          empty1.push(test1);
          let group1 = empty1[0] + "..."//这里只显示两行，超出的用...表示
          rowCut1.splice(1, 1, group);
          row1 = rowCut1;
        }
        for (let i = 0; i < row1.length; i++) {
          const metrics = cxt.measureText(row1[i])
        // console.log('metrics', metrics, ele.x, ele.y)
          cxt.fillText(row1[i], ele.x, ele.y+i*30, metrics + 5);
          // cxt.fillText(row[i], ele.x, ele.y + i * 30);
        }
        
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        // debugger
        break;

      case "txt2":
        // debugger
        cxt.setFillStyle(ele.color);
        cxt.setFontSize(ele.fontSize);
        let chr = ele.text.split("");
        let row = [];
        let temp = "";
        for (let i = 0; i < chr.length; i++) {
          if (cxt.measureText(temp).width < ele.width) {
            temp += chr[i];
          } else {
            i--;
            row.push(temp);
            temp = "";
          }
        }
        row.push(temp);
        if (row.length > 3) {//最多换行2行
          let rowCut = row.slice(0, 3);
          let rowPart = rowCut[1];
          let test = "";
          let empty = [];
          for (let i = 0; i < rowPart.length; i++) {
            if (cxt.measureText(test).width < ele.width - 20) {
              test += rowPart[i];
            } else {
              break;
            }
          }
          empty.push(test);
          let group = empty[0] + "..."//这里只显示两行，超出的用...表示
          rowCut.splice(1, 1, group);
          row = rowCut;
        }
        for (let i = 0; i < row.length; i++) {
          // debugger
          console.log(ele.x, ele.y)
          cxt.fillText(row[i], ele.x, ele.y + i * 30);
        }
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        break;
      case "txt3":
        cxt.setFillStyle(ele.color);
        cxt.setFontSize(ele.fontSize);
        cxt.setTextAlign('center')
        // const metrics = cxt.measureText(ele.text)
        // console.log('metrics',metrics,ele.x,ele.y)
   

        cxt.fillText(ele.text, ele.x, ele.y);
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        // debugger
        break;
      case "txt4":
        cxt.setFillStyle(ele.color);
        cxt.setFontSize(ele.fontSize);
        // cxt.font = `normal bold 40px sans-serif`;
        // cxt.setTextAlign('center')
        // const metrics = cxt.measureText(ele.text)
        // console.log('metrics',metrics,ele.x,ele.y)
        cxt.fillText(ele.text, ele.x, ele.y+0.7);
        cxt.fillText(ele.text, ele.x+0.7, ele.y);
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        // debugger
        break;
      case "dashLine":
        cxt.setLineWidth(1)
        cxt.setStrokeStyle(ele.color);
        cxt.beginPath();
        cxt.setLineDash([4, 2]);
        cxt.moveTo(ele.x, ele.y);
        cxt.lineTo(ele.toX, ele.toY);
        cxt.stroke();
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        break;
      case "solid":
        cxt.setLineWidth(1)
        cxt.setStrokeStyle(ele.color);
        cxt.beginPath();
        cxt.moveTo(ele.x, ele.y);
        cxt.lineTo(ele.toX, ele.toY);
        cxt.stroke();
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        break;
      case "base64Img":
        wx.downloadFile({
          url: ele.url,
          success: function (res) {
            cxt.drawImage(res.tempFilePath, ele.x, ele.y, ele.width, ele.height);
            console.log("suc " + (idx - 1));
          },
          fail: function (e) {
            console.log(e)
          },
          complete: function () {
            console.log("com " + (idx - 1));
            _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
          }
        });
        break;

      case "rect":
        cxt.setFillStyle(ele.color);
        cxt.fillRect(ele.x, ele.y, ele.width, ele.height);
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        break;
      case "circle":
        cxt.beginPath();
        cxt.arc(ele.x, ele.y, ele.r, 0, Math.PI * 2, true);
        cxt.closePath();
        cxt.strokeStyle = ele.color;
        cxt.lineWidth = 16;
        cxt.stroke();
        _this.drawPostDetail(cxt, drawEle, idx, drawWidth, drawHeight, callback);
        break;
    }
  },
  //阿里云上传签名及参数
  aliyunUploadToken() {
    let that = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/aliyunoss/getUploadToken',
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        that.setData({
          uploadParams: res.data.model
        })
      }
    })
  },
  reGetToken() {
    let that = this;
    let promise = new Promise((resolve, reject) => {
      let now = new Date().getTime() / 1000 - 30
      if (now > Number(that.data.uploadParams.expire)) {
        wx.request({
          url: cf.config.pageDomain + '/applet/mobile/aliyunoss/getUploadToken',
          header: {
            "Content-Type": "application/json"
          },
          success: function (res) {
            that.setData({
              uploadParams: res.data.model
            })
            resolve({ policy: res.data.model.policy, signature: res.data.model.signature })
          }
        })
      } else {
        resolve({ policy: that.data.uploadParams.policy, signature: that.data.uploadParams.signature })
      }
    })
    return promise
  },
  //海报上传到阿里云
  aliUpload(tempFilePath, type = 'card', isSingle = true, e) {
    let newTempFilePath = tempFilePath
    if (tempFilePath.constructor == Array) {
      tempFilePath = tempFilePath[0]
    }
    var ctx = this;
    // wx.showLoading({
    //   title: '上传中...',
    // });
    
    let arr = tempFilePath.split('.')
    let formatFileName
    if (isSingle) {
      formatFileName = wx.getStorageSync('userId')
    } else {
      // formatFileName = wx.getStorageSync('userId')+ '/' + new Date().getTime() + '.' + arr[arr.length - 1]
      formatFileName = wx.getStorageSync('userId')
    }
    let newFileName = `/image/poster/${type}/${formatFileName}/${formatFileName}.${arr[arr.length - 1]}`;
    const a = ctx.data.uploadParams
    let newFilePath = ctx.data.uploadParams.host + "/" + a.dir + newFileName;
    ctx.reGetToken().then(upData => {
      wx.uploadFile({
        url: ctx.data.uploadParams.host,
        name: 'file',
        filePath: tempFilePath,
        header: {
          "Content-Type": "multipart/form-data"
        },
        formData: {
          OSSAccessKeyId: a.accessid,
          policy: upData.policy,
          signature: upData.signature,
          key: a.dir + newFileName,
          success_action_status: 200
        },
        success: function (res) {
          if (res.statusCode == 200) {
            ctx.updataPoster(type,newFilePath)
            ctx.getPoster()
          } else if (res.statusCode == 403) {
            wx.hideLoading();
            if (newTempFilePath && type) {
              aliUpload(newTempFilePath, type, isSingle)
            } else {
              wx.showToast({
                title: '上传通行证过期，请重新上传并勿在图片选择界面停留过久',
                icon: 'none'
              })
            }

          } else {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败，请检查网络后重新上传',
              icon: 'none'
            })
          }
        },
        fail: function (res) {
          wx.hideLoading();
          wx.showToast({
            title: '网络出错',
            icon: 'none'
          })
        }
      })
    })
  },
  //更新海报
  updataPoster(type,url){
    //businessCardPosterUrl 名片海报
    //personalityPosterUrl 个性海报
    var _this=this
    let id = wx.getStorageSync('employee').id
    let posterUrl = type == 'card'?'businessCardPosterUrl':'personalityPosterUrl'
    wx.request({
      url:`${cf.config.pageDomain}applet/mobile/visitcard/employee/modifyEmployeeInfo?id=${id}&${posterUrl}=${url}`,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        // if(type=='card'){
        //   // debugger
        //   _this.setData({
        //     commonStylePosterUrl:`${url}?timer=${new Date().getTime()}`
        //   })
        // }
        // if(type=='special'){
        //   _this.setData({
        //     posterUrl:`${url}?timer=${new Date().getTime()}`
        //   })
        // }
        // wx.hideLoading();
      }
    })
  },
  //获取海报数据
  getPoster(){
    var _this = this
    let id = wx.getStorageSync('employee').id
    wx.request({
      url:`${cf.config.pageDomain}applet/mobile/visitcard/employee/getEmployeePosterInfoById?id=${id}`,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        let {personalityPosterUrl,businessCardPosterUrl} = res.data.model
        _this.setData({
          posterUrl:personalityPosterUrl?`${personalityPosterUrl}?timer=${new Date().getTime()}`:'',
          commonStylePosterUrl:businessCardPosterUrl?`${businessCardPosterUrl}?timer=${new Date().getTime()}`:''
        })
        // if(_this.data.lock){
        //   wx.downloadFile({
        //     url:personalityPosterUrl,
        //     success:function(ret){
        //       _this.saveImageToAlbum(ret.tempFilePath)
        //       // _this.setData({
        //       //   lock:false,
        //       //   textList:[]
        //       // })
        //     }
        //   })
        // }
        if(_this.data.commonStylePosterUrl==''||_this.data.posterUrl==''){
          _this.getUserInfo()
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  //  this.onLoad();
    var ctx = this
    app.routerIntercept()
    let updataCard1 = wx.getStorageSync('updataCard1')
    let updataCard2 = wx.getStorageSync('updataCard2')
    this.getPoster()
    if(updataCard1&&updataCard2){
      ctx.getUserInfo(false);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onEditCard(){
    let employee = wx.getStorageSync('employee')
    wx.navigateTo({
      url:'/pages/sales/look_card/edit_card'
    });
    //收集用户编辑名片信息
    app.globalData.sensors.track('1005', {
      account_id: wx.getStorageSync('userId'),
      role:employee?'置业顾问':'用户'
     });
  },
  onEditSetting(){
    let employee = wx.getStorageSync('employee')
    wx.navigateTo({
      url:'../../sys_setting/welword_setting/welword_setting'
    });
    //收集用户编辑欢迎语
    app.globalData.sensors.track('1007', {
      account_id: wx.getStorageSync('userId'),
      role:employee?'置业顾问':'用户'
     });
  },

  onShareAppMessage:function(e){
    
    let {path,eid} = e.target.dataset
    let employee = wx.getStorageSync('employee')
    let {id,headPic,welcomeSpeech,shareSpeech,name} = employee
    var ctx = this;
    //收集用户分享名片信息
    app.globalData.sensors.track('1001', {
      account_id: wx.getStorageSync('userId'),
      role:employee?'置业顾问':'用户'
     });
    if (e.from == "button" && id) {
      path = `${path}?eId=${id}&source=1`
      console.log(path)
      // util.addBehaviorTrail(eid, 3);
      //path 添加客户来源
      path += `&fromOpenId=${app.globalData.myOpenid}&fromNickName=${app.globalData.userInfo.nickName}&forwardType=page_card`;
      let shareObj = {
        title: shareSpeech||`你好，我是置业地产的${name},很高兴为您服务！`,
        path: path,
        imageUrl: headPic,
        success: function(res) {},
        fail: function(res) {}
      };
      // debugger
      return shareObj;
    }
  }

  /**
   * 用户点击右上角
   */
  // onShareAppMessage: function () {

  // }
}))